const HttpGenerate = require('../http/httpGenerate')
const axios = require("axios")

/**
 * 最简单版本的API使用
 * 查询价格 余额 下单
 * instId 表示商品名称
 * */

//@Bean
class YqOkexApiService {


	//@Value(YqOkexApiService.API_KEY)
	API_KEY;

	//@Value(YqOkexApiService.API_SECRET)
	API_SECRET;

	//@Value(YqOkexApiService.API_PASS)
	API_PASS;

	//@Value(value=YqOkexApiService.timeout,force=false)
	timeout=2000;

	beanInit(){
		this.http =  HttpGenerate(this.API_KEY,this.API_SECRET,this.API_PASS);
		axios.defaults.timeout =  this.timeout;
	}

	/**
	*
	* 查询货币的价格
	* 默认查询：BTC-USDT
	* 
	*/
	async getTicker(instId='BTC-USDT'){
		const {last} =  await this.http.getTicker(instId);
		return last;
	}

	/**
	 *	查询账户内的币种余额
	 * 	默认查询USDT
	 * 
	*/
	async getBalance(coinName){
		if(!coinName){
			throw `getBalance(coinName) must be pass coinName example USDT`
		}
		const {details:[d]} = await this.http.getAccounts(coinName);
		return d.availEq;
	}


	/**
	 * 购买
	 * example: buy('BTC-USDT',4) 购买了4U的BTC
	 * */
	async buy(instId,size){
		return await this._marketOrder('buy',instId,size)
	}


	/**
	 * 出售
	 * example: sell('BTC-USDT',0.0001) 出售了万分之1个BTC
	 * */
	async sell(instId,size){
		return await this._marketOrder('sell',instId,size)
	}


	/**
	*
	*  market：市价下单 
	*  side: 'buy' 表示购买  'sell' 表示出售
	*  size 表示数量
	*  返回 {"clOrdId":"","ordId":"445394174840553478","sCode":"0","sMsg":"","tag":""}
	*/
	async _marketOrder(side,instId,size){
		return this.http.marketOrder(instId,'cash',side,'market',size)
	}


	/**
	 * 获取市场恐慌情绪
	 * 0~25为极度恐慌，75~100为极度 ..
	 * return Integer 
	 * */
	async getMarketSentiment(){
		const {data} = await axios.get('https://api.alternative.me/fng/')
		return +data.data[0].value;
	}

}

module.exports = {YqOkexApiService}